package com.ruoyi.project.system.goods.goods.controller;

import java.math.BigDecimal;
import java.util.*;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.brand.service.IBrandService;
import com.ruoyi.project.system.file.domain.UploadFile;
import com.ruoyi.project.system.file.service.IUploadFileService;
import com.ruoyi.project.system.goods.fee.domain.GoodsPostFee;
import com.ruoyi.project.system.goods.fee.service.IGoodsPostFeeService;
import com.ruoyi.project.system.goods.goods.domain.GoodsDto;
import com.ruoyi.project.system.goods.goods.domain.GoodsGoods;
import com.ruoyi.project.system.goods.goods.service.IGoodsGoodsService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.goods.img.domain.GoodsImg;
import com.ruoyi.project.system.goods.img.enums.GoodsImgType;
import com.ruoyi.project.system.goods.img.service.IGoodsImgService;
import com.ruoyi.project.system.goods.product.domain.GoodsProduct;
import com.ruoyi.project.system.goods.product.enums.GoodsProductStatus;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.goodsclass.domain.GoodsClass;
import com.ruoyi.project.system.goodsclass.service.IGoodsClassService;
import com.ruoyi.project.system.params.domain.TypeParams;
import com.ruoyi.project.system.params.service.ITypeParamsService;
import com.ruoyi.project.system.spec.service.IGoodsSpecService;
import com.ruoyi.project.system.tspec.domain.TypeSpec;
import com.ruoyi.project.system.tspec.service.ITypeSpecService;
import com.ruoyi.project.system.tsvalue.service.ITypeSpecValueService;
import com.ruoyi.project.system.type.domain.GoodsType;
import com.ruoyi.project.system.type.service.IGoodsTypeService;
import com.ruoyi.project.system.value.service.IGoodsSpecValueService;

/**
 * 商品Controller
 * 
 * @author LCL
 * @date 2020-06-12
 */
@Controller
@RequestMapping("/system/goods")
public class GoodsGoodsController extends BaseController
{
    private String prefix = "system/goods";

    @Autowired
    private IGoodsGoodsService goodsGoodsService;
    @Autowired
    private IGoodsTypeService goodsTypeService;
    @Autowired
    private IGoodsClassService goodsClassService;
    @Autowired
    private IBrandService brandService;
    @Autowired
    private ITypeSpecService typeSpecService;
    @Autowired
    private IGoodsSpecService goodsSpecService;
    @Autowired
    private IGoodsSpecValueService goodsSpecValueService;
    @Autowired
    private ITypeSpecValueService typeSpecValueService;
    @Autowired
    private ITypeParamsService typeParamsService;
    @Autowired
    private IUploadFileService uploadFileService;
    @Autowired
    private IGoodsProductService goodsProductService;
    @Autowired
    private IGoodsImgService goodsImgService;
    @Autowired
    private IGoodsPostFeeService goodsPostFeeService;

    @RequiresPermissions("system:goods:view")
    @GetMapping()
    public String goods()
    {
        return prefix + "/goods";
    }

    /**
     * 查询商品列表
     */
    @RequiresPermissions("system:goods:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GoodsGoods goodsGoods)
    {
        startPage();
        List<GoodsDto> list = goodsGoodsService.selectGoodsGoodsList(goodsGoods);
        return getDataTable(list);
    }

//    /**
//     * 导出商品列表
//     */
//    @RequiresPermissions("system:goods:export")
//    @Log(title = "商品", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    @ResponseBody
//    public AjaxResult export(GoodsGoods goodsGoods)
//    {
//        List<GoodsDto> list = goodsGoodsService.selectGoodsGoodsList(goodsGoods);
//        ExcelUtil<GoodsGoods> util = new ExcelUtil<GoodsGoods>(GoodsGoods.class);
//        return util.exportExcel(list, "goods");
//    }

    /**
     * 新增商品
     */
    @GetMapping("/add")
    public String add(ModelMap map)
    {
        map.put("goodsTypeList",this.goodsTypeService.findAll());
        map.put("goodsClassName","请选择分类");
        map.put("brand",this.brandService.findAll());
        return prefix + "/add";
    }

    /**
     * 新增保存商品
     */
    @RequiresPermissions("system:goods:add")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(GoodsGoods goodsGoods, String[] imgBannerUrl, String[] imgBannerRealPath,
                              String[] imgDetailsUrl, String[] imgDetailsRealPath,
                              String products)
    {
        //判断商品的分类是不是二级分类
        GoodsClass goodsClass = this.goodsClassService.selectGoodsClassById(goodsGoods.getClassId());
        if(StringUtils.isBlank(goodsClass.getParentId())){
            return AjaxResult.error("请选择二级分类");
        }
        goodsGoods.setMonthlySales(0L);

        //判断是否使用规格
        if(goodsGoods.getHasSpec().equals(1)){
            goodsGoods.setSpec("[{\"spec_name\":\"通用\",\"spec_values\":[{\"spec_value_name\":\"通用\"}]}]");
        }

        //添加商品信息
        goodsGoodsService.insertGoodsGoods(goodsGoods);
//        //主图信息修改
//        this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(goodsGoods.getMainUrlReal()),new UploadFile(null,null,null,goodsGoods.getId()));
//        if(imgBannerRealPath!=null){
//            this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgBannerRealPath),new UploadFile(null,null,null,goodsGoods.getId()));
//        }
//        if(imgBannerRealPath!=null){
//            this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgDetailsRealPath),new UploadFile(null,null,null,goodsGoods.getId()));
//        }

        //总库存
        int sumStock = 0;

        //添加产品信息

        List<Map<String,Object>> productArr = (List<Map<String,Object>>) JSON.parse(products);
        for(Map<String,Object> product:productArr){
            GoodsProduct goodsProduct = new GoodsProduct();
            goodsProduct.setIcon((String) product.get("icon"));
            goodsProduct.setIconReal((String) product.get("iconReal"));
            goodsProduct.setGoodsId(goodsGoods.getId());
            goodsProduct.setStock(Integer.parseInt((String) product.get("stock")));
            goodsProduct.setIsDefault((boolean)product.get("isDefault")?1:0);
            String spec = (String) product.get("spec");
            //通过规格获取名称
            StringBuffer bufName = new StringBuffer();
            if (spec.contains("*") && spec.contains(":")) {
                String[] str = StringUtils.split(spec, "*");
                for (String temp : str) {
                    String[] s = StringUtils.split(temp, ":");
//						name += s[1] + " ";
                    bufName.append(s[1] + " ");
                }
            } else if (spec.contains(":")) {
                String[] s = StringUtils.split(spec, ":");
//					name = s[1];
                bufName.append(s[1]);
            }
            if(goodsGoods.getHasSpec().equals(1)){
                goodsProduct.setName("通用");
            }else{
                goodsProduct.setName(bufName.toString());
            }
            goodsProduct.setNumSale(0L);
            goodsProduct.setPriceN(new BigDecimal((String) product.get("priceN")));
            goodsProduct.setPriceO(new BigDecimal((String) product.get("priceO")));
            goodsProduct.setPriceVip(new BigDecimal((String) product.get("priceVip")));
            goodsProduct.setStatus(GoodsProductStatus.NORMAL.getValue());
            //判断是否使用规格
            if(goodsGoods.getHasSpec().equals(1)){
                goodsProduct.setSpec("通用:通用");
            }else{
                goodsProduct.setSpec(spec);
            }
            this.goodsProductService.insertGoodsProduct(goodsProduct);
            sumStock+=goodsProduct.getStock();
            //主图信息修改
//            this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(goodsProduct.getIconReal()),new UploadFile(null,null,null,goodsProduct.getId()));
        }

        //更新产品的库存信息
        GoodsGoods updateGoods = new GoodsGoods();
        updateGoods.setId(goodsGoods.getId());
        updateGoods.setStock(Integer.toUnsignedLong(sumStock));
        this.goodsGoodsService.updateGoodsGoods(updateGoods);

        if(imgBannerUrl!=null){
            //商品轮播图
            for (int i = 0; i < imgBannerUrl.length; i++) {
                GoodsImg goodsImg = new GoodsImg();
                goodsImg.setSort(Integer.toUnsignedLong(i));
                goodsImg.setGoodsId(goodsGoods.getId());
                goodsImg.setUrl(imgBannerUrl[i]);
                goodsImg.setUrlRealPath(imgBannerRealPath[i]);
                goodsImg.setType(GoodsImgType.BANNER.getValue());
                this.goodsImgService.insertGoodsImg(goodsImg);
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgBannerRealPath[i]),new UploadFile(null,null,null,goodsImg.getId()));
            }
        }
        if(imgDetailsUrl!=null){
            //商品详情
            for (int i = 0; i < imgDetailsUrl.length; i++) {
                GoodsImg goodsImg = new GoodsImg();
                goodsImg.setSort(Integer.toUnsignedLong(i));
                goodsImg.setGoodsId(goodsGoods.getId());
                goodsImg.setUrl(imgDetailsUrl[i]);
                goodsImg.setUrlRealPath(imgDetailsRealPath[i]);
                goodsImg.setType(GoodsImgType.DETAILS.getValue());
                this.goodsImgService.insertGoodsImg(goodsImg);
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgDetailsRealPath[i]),new UploadFile(null,null,null,goodsImg.getId()));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改商品
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        GoodsDto goodsGoods = goodsGoodsService.findGoodsDtoById(id);
        mmap.put("goodsGoods", goodsGoods);
        mmap.put("goodsTypeList",this.goodsTypeService.findAll());
        mmap.put("brand",this.brandService.findAll());
        List<GoodsProduct> goodsProductList = this.goodsProductService.findListByGoodsId(id);
        mmap.put("goodsProducts",goodsProductList);
        mmap.put("goodsBanner",this.goodsImgService.findListByGoodsIdAndType(id,GoodsImgType.BANNER.getValue()));
        mmap.put("goodsDetails",this.goodsImgService.findListByGoodsIdAndType(id,GoodsImgType.DETAILS.getValue()));
        mmap.put("typeParams",typeParamsService.findListByTypeId(goodsGoods.getTypeId()));
        mmap.put("productNum",goodsProductList.size());
        return prefix + "/edit";
    }

    /**
     * 修改保存商品
     */
    @RequiresPermissions("system:goods:edit")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional
    public AjaxResult editSave(GoodsGoods goodsGoods, String[] imgBannerUrl, String[] imgBannerRealPath,
                               String[] imgDetailsUrl, String[] imgDetailsRealPath,
                               String products)
    {
        //判断商品的分类是不是二级分类
        GoodsClass goodsClass = this.goodsClassService.selectGoodsClassById(goodsGoods.getClassId());
        if(StringUtils.isBlank(goodsClass.getParentId())){
            return AjaxResult.error("请选择二级分类");
        }


        //判断是否使用规格
        if(goodsGoods.getHasSpec().equals(1)){
            goodsGoods.setSpec("[{\"spec_name\":\"通用\",\"spec_values\":[{\"spec_value_name\":\"通用\"}]}]");
        }


        //更新商品信息
        goodsGoodsService.updateGoodsGoods(goodsGoods);

//        if(imgBannerRealPath!=null){
//            this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgBannerRealPath),new UploadFile(null,null,null,goodsGoods.getId()));
//        }
//        if(imgDetailsRealPath!=null){
//            this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgDetailsRealPath),new UploadFile(null,null,null,goodsGoods.getId()));
//        }

        //总库存
        int sumStock = 0;

        //删除数据库原本的相册资源
        this.goodsImgService.deleteByGoodsId(goodsGoods.getId());

        //添加产品信息

        if(!StringUtils.isBlank(products)){
            //删除原本存在的产品信息
            this.goodsProductService.removeByGoodsId(goodsGoods.getId());
            List<Map<String,Object>> productArr = (List<Map<String,Object>>) JSON.parse(products);
            for(Map<String,Object> product:productArr){
                GoodsProduct goodsProduct = new GoodsProduct();
                goodsProduct.setIcon((String) product.get("icon"));
                goodsProduct.setIconReal((String) product.get("iconReal"));
                goodsProduct.setStock(Integer.parseInt((String) product.get("stock")));
                goodsProduct.setGoodsId(goodsGoods.getId());
                goodsProduct.setIsDefault((boolean)product.get("isDefault")?1:0);
                String spec = (String) product.get("spec");
                //通过规格获取名称
                StringBuffer bufName = new StringBuffer();
                if (spec.contains("*") && spec.contains(":")) {
                    String[] str = StringUtils.split(spec, "*");
                    for (String temp : str) {
                        String[] s = StringUtils.split(temp, ":");
//						name += s[1] + " ";
                        bufName.append(s[1] + " ");
                    }
                } else if (spec.contains(":")) {
                    String[] s = StringUtils.split(spec, ":");
//					name = s[1];
                    bufName.append(s[1]);
                }
                if(goodsGoods.getHasSpec().equals(1)){
                    goodsProduct.setName("通用");
                }else{
                    goodsProduct.setName(bufName.toString());
                }
                goodsProduct.setNumSale(0L);
                goodsProduct.setPriceN(new BigDecimal((String) product.get("priceN")));
                goodsProduct.setPriceO(new BigDecimal((String) product.get("priceO")));
                goodsProduct.setPriceVip(new BigDecimal((String) product.get("priceVip")));
                goodsProduct.setStatus(GoodsProductStatus.NORMAL.getValue());
                //判断是否使用规格
                if(goodsGoods.getHasSpec().equals(1)){
                    goodsProduct.setSpec("通用:通用");
                }else{
                    goodsProduct.setSpec(spec);
                }
                this.goodsProductService.insertGoodsProduct(goodsProduct);
                sumStock+=goodsProduct.getStock();
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(goodsProduct.getIconReal()),new UploadFile(null,null,null,goodsProduct.getId()));
            }
        }

        //更新产品的库存信息
        GoodsGoods updateGoods = new GoodsGoods();
        updateGoods.setId(goodsGoods.getId());
        updateGoods.setStock(Integer.toUnsignedLong(sumStock));
        this.goodsGoodsService.updateGoodsGoods(updateGoods);


        if(imgBannerUrl!=null){
            //商品轮播
            for (int i = 0; i < imgBannerUrl.length; i++) {
                GoodsImg goodsImg = new GoodsImg();
                goodsImg.setSort(Integer.toUnsignedLong(i));
                goodsImg.setGoodsId(goodsGoods.getId());
                goodsImg.setUrl(imgBannerUrl[i]);
                goodsImg.setUrlRealPath(imgBannerRealPath[i]);
                goodsImg.setType(GoodsImgType.BANNER.getValue());
                this.goodsImgService.insertGoodsImg(goodsImg);
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgBannerRealPath[i]),new UploadFile(null,null,null,goodsImg.getId()));
            }
        }
        if(imgDetailsUrl!=null){
            //商品详情
            for (int i = 0; i < imgDetailsUrl.length; i++) {
                GoodsImg goodsImg = new GoodsImg();
                goodsImg.setSort(Integer.toUnsignedLong(i));
                goodsImg.setGoodsId(goodsGoods.getId());
                goodsImg.setUrl(imgDetailsUrl[i]);
                goodsImg.setUrlRealPath(imgDetailsRealPath[i]);
                goodsImg.setType(GoodsImgType.DETAILS.getValue());
                this.goodsImgService.insertGoodsImg(goodsImg);
                //主图信息修改
//                this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(imgDetailsRealPath[i]),new UploadFile(null,null,null,goodsImg.getId()));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除商品
     */
    @RequiresPermissions("system:goods:remove")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        //修改商品状态为删除
        this.goodsGoodsService.remove(ids);
        return AjaxResult.success();
    }



    /**
     * 开启规格页面
     *
     * @param id
     */
    @GetMapping("/spec")
    public String spec(String id, ModelMap mmap,String type) {

        List<TypeSpec> typeSpecList = this.typeSpecService.findListByTypeId(id);

        for(TypeSpec typeSpec:typeSpecList){
            typeSpec.setGoodsSpec(this.goodsSpecService.selectGoodsSpecById(typeSpec.getSpecId()));
            typeSpec.setTypeSpecValueDtoList(this.typeSpecValueService.findListByTypeSpecId(typeSpec.getId()));
        }

        mmap.put("specList", typeSpecList);
        mmap.put("type",type);
//		model.addAttribute();
//		req.setAttribute("specList", typeSpecList);
//		req.setAttribute("lvList", memberLevelService.query(Cnd.orderBy().asc("point")));
        return prefix+"/spec";
    }

    /**
     * 获取商品类型的详细参数
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/getParam")
    public R getParam(@RequestParam("id")String id) {

        if(!StringUtils.isBlank(id)){
            TypeParams typeParams = new TypeParams();
            typeParams.setTypeId(id);
            List<TypeParams> list = this.typeParamsService.selectTypeParamsList(typeParams);
            return R.ok().put("data", list);
        }
//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
       return R.error();
    }

    /*
     * 去设置运费
     * */
    @GetMapping("/goPostFee/{id}")
    @RequiresPermissions("mall:goodsGoods:edit")
    String goPostFee(@PathVariable("id") String id,ModelMap mmap){
        mmap.put("goodsId", id);
//        Map<String,Object> map = new HashMap<>();
//        map.put("delFlag","0");
//        map.put("goodsId", id);
        GoodsPostFee goodsPostFee = new GoodsPostFee();
        goodsPostFee.setGoodsId(id);
        List<GoodsPostFee> list = goodsPostFeeService.selectGoodsPostFeeList(goodsPostFee);
        mmap.put("postList", list);
        return prefix+"/postFees";
    }

    /**
     * 设置运费,保存
     */
    @ResponseBody
    @PostMapping("/setPostFee")
    @Transactional
    public R setPostFee(@RequestParam("datail") String datail,@RequestParam("goodsId") String goodsId){
        //删除原本存在的
        this.goodsPostFeeService.deleteByGoodsId(goodsId);

        if(!StringUtils.isBlank(datail)){
            for(String data:datail.split(",")){
                String[] da = data.split(":");
                GoodsPostFee goodsPostFee = new GoodsPostFee();
                goodsPostFee.setPostFee(new BigDecimal(da[1]));
                goodsPostFee.setName(da[0]);
                goodsPostFee.setGoodsId(goodsId);
                this.goodsPostFeeService.insertGoodsPostFee(goodsPostFee);
            }
        }
        return R.ok();
    }
}
